// leaderPerson/pages/groupDragon/Create/create.js
const {common: common} = require("../../../../common/common.js");

var dateTimePicker = require("../../leaderClosed/dateTimePicker.js");

var util = require("../../../../utils/util.js");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        repeatSub: false,
        isIOS: false,
        addVisible: false,
        //向下添加大图
        images: [],
        selectIds: [],
        //选择的商品 1504,1515
        animationData: "",
        add_index: 0,
        group_id: "",
        //复制的平台接龙id
        origin_type: 1,
        //0:平台接龙 1：团长接龙
        pro_type: "",
        //1：实物商品 2:虚拟商品
        contentItems: [ {
            type: "image",
            icon: "icon-tupian2",
            text: "添加大图"
        }, {
            type: "s_image",
            icon: "icon-leimupinleifenleileibie",
            text: "添加小图"
        }, {
            type: "video",
            icon: "icon-shipin1",
            text: "添加视频"
        }, {
            type: "textarea",
            icon: "icon-huati",
            text: "添加文字"
        } ],
        model: {
            name: "",
            active_at: "",
            active_end: "",
            img: [],
            contents: [],
            products: [],
            recommend: false
        },
        submitMsg: {
            name: "",
            active_at: "",
            active_end: "",
            img: "",
            contents: "",
            products: ""
        },
        content: "",
        copy_id: "",
        //复制的接龙id
        edit_id: "",
        //修改接龙id
        commodity_type: 1,
        //1:平台商品 2：门店商品 3:复制
        source: "",
        //只有复制的时候才赋值
        subscribeMessage: true,
        tmplIds: [],
        imgSource: 1,
        //上传图片来源
        downAdd: 0,
        downIndex: 0,
        goodsType: 1,
        //1.门店实物商品 2.门店虚拟商品
        opetype: 0,
        //是否复制
        source1: 1,
        opeT: 1
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad(options) {
        this.setData({
            commodity_type: options.type || 1,
            //复制类型直接请求接龙详情并获取当前选中商品类型
            copy_id: options.copy_id || "",
            edit_id: options.id || "",
            opeT: options.type || 1
        });
        this.initDatetime();
        //不能放在onShow()
        // 从商品库选完商品回来，要回显所填表单内容
                let info = wx.getStorageSync("leaderCreate") || "";
        if (info) {
            this.dealPageShow(info);
            //处理回显
                }
        if (options.opetype == 3) {
            this.setData({
                opetype: 3
            });
            wx.setNavigationBarTitle({
                title: "复制接龙活动"
            });
            this.getDragonDetail(options.copy_id);
        }
        if (options.id) {
            this.setData({
                opetype: 4
            });
            wx.setNavigationBarTitle({
                title: "修改团信息"
            });
            this.getDragonDetail(options.id);
        }
        this.getTmplIds();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow() {
        let that = this;
        const system = wx.getSystemInfoSync().system;
        const isIOS = system.includes("iOS");
        that.setData({
            isIOS: isIOS
        });
        if (that.data.selectIds.length) {
            //商品库选择完商品，请求商品接口
            that.getGoodLists();
        }
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload() {},
    /**
   * 
   * @param {处理页面回显} info 
   */
    dealPageShow(info) {
        let that = this;
        let res = JSON.parse(info);
        let model = that.data.model;
        Object.keys(model).forEach(key => {
            model[key] = res[key];
        });
        that.setData({
            model: model
        });
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        //console.log(version);
                if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                console.log(res);
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if (v.type == "32" && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    },
    initDatetime: function() {
        let that = this;
        // 获取完整的年月日 时分秒，以及默认显示的数组
                var stateObj = dateTimePicker.dateTimePicker(that.data.startYear, that.data.endYear);
        var endObj = dateTimePicker.dateTimePicker(that.data.startYear, that.data.endYear);
        // 精确到分的处理，将数组的秒去掉
                stateObj.dateTimeArray.pop();
        stateObj.dateTime.pop();
        endObj.dateTimeArray.pop();
        endObj.dateTime.pop();
        that.setData({
            startDateTime: stateObj.dateTime,
            startDateTimeArray: stateObj.dateTimeArray,
            endDateTimeArray: endObj.dateTimeArray,
            endDateTime: endObj.dateTime,
            ["model.active_at"]: `${stateObj.dateTimeArray[0][stateObj.dateTime[0]]}-${stateObj.dateTimeArray[1][stateObj.dateTime[1]]}-${stateObj.dateTimeArray[2][stateObj.dateTime[2]]} ${stateObj.dateTimeArray[3][stateObj.dateTime[3]]}:${stateObj.dateTimeArray[4][stateObj.dateTime[4]]}`,
            ["model.active_end"]: `${endObj.dateTimeArray[0][endObj.dateTime[0]]}-${endObj.dateTimeArray[1][endObj.dateTime[1]]}-${endObj.dateTimeArray[2][endObj.dateTime[2]]} ${endObj.dateTimeArray[3][endObj.dateTime[3]]}:${endObj.dateTimeArray[4][endObj.dateTime[4]]}`
        });
    },
    /**
   * 
   * @param {接龙时间} e 
   */
    changeDateTime(e) {
        let type = e.currentTarget.dataset.name || "startDateTime";
        if (type == "startDateTime") {
            this.setData({
                startDateTime: e.detail.value,
                ["model.active_at"]: `${this.data.startDateTimeArray[0][e.detail.value[0]]}-${this.data.startDateTimeArray[1][e.detail.value[1]]}-${this.data.startDateTimeArray[2][e.detail.value[2]]} ${this.data.startDateTimeArray[3][e.detail.value[3]]}:${this.data.startDateTimeArray[4][e.detail.value[4]]}`
            });
            this.onBlur("", "active_at");
        }
        if (type == "endDateTime") {
            this.setData({
                endDateTime: e.detail.value,
                ["model.active_end"]: `${this.data.endDateTimeArray[0][e.detail.value[0]]}-${this.data.endDateTimeArray[1][e.detail.value[1]]}-${this.data.endDateTimeArray[2][e.detail.value[2]]} ${this.data.endDateTimeArray[3][e.detail.value[3]]}:${this.data.endDateTimeArray[4][e.detail.value[4]]}`
            });
            this.onBlur("", "active_end");
        }
    },
    /**
   * 
   * @param {改变列时间触发} e 
   */
    changeDateTimeColumn(e) {
        let type = e.currentTarget.dataset.name || "startDateTime";
        if (type == "startDateTime") {
            var arr = this.data.startDateTime, dateArr = this.data.startDateTimeArray;
            arr[e.detail.column] = e.detail.value;
            dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
            this.setData({
                startDateTimeArray: dateArr,
                startDateTime: arr
            });
        }
        if (type == "endDateTime") {
            var arr = this.data.endDateTime, dateArr = this.data.endDateTimeArray;
            arr[e.detail.column] = e.detail.value;
            dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
            this.setData({
                endDateTimeArray: dateArr,
                endDateTime: arr
            });
        }
    },
    /**
   * 获取商品列表
   * @param {}  
   */
    getGoodLists: function() {
        let that = this;
        let source = that.data.commodity_type != 3 ? that.data.commodity_type : that.data.source;
        if (that.data.commodity_type == 2 && that.data.goodsType == 2) {
            source = 3;
        }
        if (that.data.opetype == 3 || that.data.opetype == 4) {
            source = that.data.opeT;
        }
        console.log(source);
        common.request({
            endpoint: "product/aggregate-product-info",
            data: {
                product_ids: that.data.selectIds.join(","),
                source: source,
                type: 1
            },
            method: "post",
            success(res) {
                that.setData({
                    ["model.products"]: res.extra
                });
                that.onBlur("", "products");
            }
        });
    },
    /**
   * 获取群接龙详情-复制使用
   * id:接龙id
   */
    getDragonDetail: function(id) {
        let that = this;
        common.request({
            endpoint: "Leader/leader-group/view",
            data: {
                id: id
            },
            method: "post",
            success(res) {
                if (res.code == 0) {
                    let result = res.extra;
                    let model = that.data.model;
                    Object.keys(model).forEach(key => {
                        model[key] = result[key];
                    });
                    model.contents = result.content || [];
                    that.setData({
                        model: model,
                        source: that.data.commodity_type == 3 ? result.source : "",
                        //复制时复制商品类型
                        origin_type: result.origin_type,
                        pro_type: result.pro_type,
                        commodity_type: result.source,
                        goodsType: result.source == 3 ? 2 : 1,
                        source1: result.source,
                        opeT: result.source
                    });
                }
            }
        });
    },
    /**
   * 上传视频 
   */
    chooseVideo: function(index = -1) {
        let that = this;
        wx.chooseMedia({
            count: 1,
            mediaType: [ "video" ],
            sourceType: [ "album", "camera" ],
            maxDuration: 30,
            camera: "back",
            success(res) {
                if (res.tempFiles.length) {
                    res.tempFiles.forEach(item => {
                        that.uploadVideo(item.tempFilePath, index);
                    });
                    wx.showLoading({
                        title: "正在上传..."
                    });
                }
            }
        });
    },
    NuploadImage: function() {
        this.setData({
            imgSource: 1
        });
        this.uploadImage();
    },
    /**
   * 小图上传图片
   * @param {*} e 
   */
    sUploadImage: function(e) {
        let type = "s_image";
        let index = e.currentTarget.dataset.index;
        this.setData({
            imgSource: 2,
            downAdd: 0
        });
        this.uploadImage(type, index);
    },
    /**
   * 
   * @param {*上传类型} type 
   * @param {*小图使用} index 
   * @param {*向下插入元素index} down_index 
   */
    uploadImage: function(type = "", index, down_index = "") {
        let that = this;
        if (that.data.imgSource == 1) {
            wx.chooseImage({
                count: 6,
                sizeType: [ "original", "compressed" ],
                sourceType: [ "album", "camera" ],
                success(res) {
                    if (res.tempFilePaths.length) {
                        if (res.tempFilePaths.length + that.data.model.img.length > 6) {
                            wx.showModal({
                                title: "提示",
                                content: "接龙图片最多传6张",
                                complete: res => {}
                            });
                        } else {
                            let count = 0;
                            let length = res.tempFilePaths.length;
                            wx.showLoading({
                                title: "正在上传..."
                            });
                            that.uploadFile(res.tempFilePaths, type, index, down_index, count, length);
                            // res.tempFilePaths.forEach(item => {
                            //   that.uploadFile(item, type, index, down_index)
                            // })
                                                }
                    }
                }
            });
        } else {
            wx.chooseImage({
                sizeType: [ "original", "compressed" ],
                sourceType: [ "album", "camera" ],
                success(res) {
                    // res.tempFilePaths.forEach(item => {
                    //   that.uploadFile(item, type, index, down_index)
                    // })
                    wx.showLoading({
                        title: "正在上传..."
                    });
                    let count = 0;
                    let length = res.tempFilePaths.length;
                    that.uploadFile(res.tempFilePaths, type, index, down_index, count, length);
                },
                fail: res => {
                    let arr = that.data.model.contents;
                    if (that.data.downAdd == 1) {
                        arr.splice(that.data.downIndex, 1);
                    }
                    that.setData({
                        ["model.contents"]: arr
                    });
                }
            });
        }
    },
    uploadFile: function(tempFilePath, type, index, down_index = "", count, length) {
        var that = this;
        let domian = app.globalData.domain;
        wx.uploadFile({
            url: domian + "Media/manage/image-upload",
            filePath: tempFilePath[count],
            name: "file",
            formData: {
                method: 0
            },
            header: {
                "Content-Type": "multipart/form-data",
                uniacid: wx.getStorageSync("uniacid")
            },
            success: function(res) {
                // wx.hideLoading();
                let data = JSON.parse(res.data);
                if (data.code != -1) {
                    let arr = that.data.model.img;
                    let obj = {};
                    if (type != "image" && type != "s_image") {
                        arr = that.data.model.img;
                        arr.push(data.extra);
                        that.setData({
                            ["model.img"]: arr
                        });
                        that.onBlur("", "img");
                    } else {
                        if (type == "image") {
                            arr = that.data.model.contents;
                            obj = {
                                type: type,
                                content: data.extra,
                                status: "done",
                                type_text: "大图"
                            };
                            if (down_index) {
                                arr.splice(down_index, 0, obj);
                            } else {
                                arr.push(obj);
                            }
                        } else if (type == "s_image") {
                            //小图图片路径是数组
                            arr = that.data.model.contents;
                            let item = !down_index ? arr[index] : arr[down_index];
                            let content = item ? item["content"] : [];
                            content.push(data.extra);
                            obj = {
                                type: type,
                                content: content,
                                status: "done",
                                type_text: "小图"
                            };
                            if (down_index) {
                                arr[down_index] = obj;
                            } else {
                                if (!item) {
                                    arr.push(obj);
                                }
                            }
                        }
                        that.setData({
                            ["model.contents"]: arr
                        });
                        that.onBlur("", "contents");
                    }
                } else {
                    wx.showModal({
                        title: "错误提示",
                        content: data.message,
                        showCancel: false,
                        success: function(res) {}
                    });
                }
            },
            fail: function(res) {
                wx.hideLoading();
                wx.showModal({
                    title: "错误提示",
                    content: "上传图片失败",
                    showCancel: false,
                    success: function(res) {}
                });
            },
            complete: function(e) {
                count++;
                if (count == length) {
                    wx.hideLoading({});
                } else {
                    that.uploadFile(tempFilePath, type, index, down_index, count, length);
                }
            }
        });
    },
    //上传图片
    // uploadFile: function (tempFilePath, type, index, down_index = '') {
    //   var that = this;
    //   let domian = app.globalData.domain;
    //   wx.uploadFile({
    //     url: domian + 'Media/manage/image-upload',
    //     filePath: tempFilePath,
    //     name: 'file',
    //     formData: {
    //       method: 0
    //     },
    //     header: {
    //       "Content-Type": "multipart/form-data",
    //       uniacid: wx.getStorageSync('uniacid'),
    //     },
    //     success: function (res) {
    //       wx.hideLoading();
    //       let data = JSON.parse(res.data);
    //       if (data.code != -1) {
    //         let arr = that.data.model.img;
    //         let obj = {}
    //         if (type != 'image' && type != 's_image') {
    //           arr = that.data.model.img;
    //           arr.push(data.extra)
    //           that.setData({
    //             ['model.img']: arr
    //           })
    //           that.onBlur('', 'img')
    //         } else {
    //           if (type == 'image') {
    //             arr = that.data.model.contents;
    //             obj = {
    //               type: type,
    //               content: data.extra,
    //               status: 'done',
    //               type_text: '大图'
    //             }
    //             if (down_index) {
    //               arr.splice(down_index, 0, obj)
    //             } else {
    //               arr.push(obj)
    //             }
    //           } else if (type == 's_image') { //小图图片路径是数组
    //             arr = that.data.model.contents;
    //             let item = !down_index ? arr[index] : arr[down_index];
    //             let content = item ? item['content'] : [];
    //             content.push(data.extra)
    //             obj = {
    //               type: type,
    //               content: content,
    //               status: 'done',
    //               type_text: '小图'
    //             }
    //             if (down_index) {
    //               arr[down_index] = obj
    //             } else {
    //               if (!item) {
    //                 arr.push(obj)
    //               }
    //             }
    //           }
    //           that.setData({
    //             ['model.contents']: arr
    //           })
    //           that.onBlur('', 'contents')
    //         }
    //       } else {
    //         wx.showModal({
    //           title: '错误提示',
    //           content: data.message,
    //           showCancel: false,
    //           success: function (res) { }
    //         })
    //       }
    //     },
    //     fail: function (res) {
    //       wx.hideLoading();
    //       wx.showModal({
    //         title: '错误提示',
    //         content: '上传图片失败',
    //         showCancel: false,
    //         success: function (res) { }
    //       })
    //     }
    //   })
    // },
    /**
   * 上传视频
   * @param {*文件} tempFilePath 
   * @param {*向下插入Index} index 
   */
    uploadVideo: function(tempFilePath, index = -1) {
        var that = this;
        let domian = app.globalData.domain;
        wx.uploadFile({
            url: domian + "Media/manage/video-upload",
            filePath: tempFilePath,
            name: "file",
            header: {
                "Content-Type": "multipart/form-data",
                uniacid: wx.getStorageSync("uniacid")
            },
            success: function(res) {
                wx.hideLoading();
                let data = JSON.parse(res.data);
                if (data.code != -1) {
                    let arr = that.data.model.contents;
                    let obj = {
                        type: "video",
                        content: data.extra[0],
                        status: "done",
                        type_text: "视频"
                    };
                    if (index >= 0) {
                        arr.splice(index, 0, obj);
                    } else {
                        arr.push(obj);
                    }
                    that.setData({
                        ["model.contents"]: arr,
                        addVisible: false
                    });
                    that.onBlur("", "contents");
                } else {
                    wx.showModal({
                        title: "错误提示",
                        content: data.message,
                        showCancel: false,
                        success: function(res) {}
                    });
                }
            },
            fail: function(res) {
                wx.hideLoading();
                wx.showModal({
                    title: "错误提示",
                    content: "上传视频失败",
                    showCancel: false,
                    success: function(res) {}
                });
            }
        });
    },
    /**
   * 删除图片
   */
    delImage: function(e) {
        let index = e.currentTarget.dataset.index;
        let images = this.data.model.img;
        images.splice(index, 1);
        this.setData({
            ["model.img"]: images
        });
        this.onBlur("", "img");
    },
    /**
   * 删除小图中单个图片
   * @param {*} e 
   * key:当前图片小标
   * index:当前数组下标
   */
    delSImage: function(e) {
        let index = e.currentTarget.dataset.index;
        let key = e.currentTarget.dataset.key;
        let arr = this.data.model.contents;
        arr[index]["content"].splice(key, 1);
        this.setData({
            ["model.contents"]: arr
        });
    },
    /**
   * 添加模块
   */
    addModule: function(e) {
        let type = e.currentTarget.dataset.type;
        let type_text = "";
        if (type == "image") {
            type_text = "大图";
        } else if (type == "s_image") {
            type_text = "小图";
        } else if (type == "video") {
            type_text = "视频";
        } else if (type == "textarea") {
            type_text = "文字";
        }
        let arr = this.data.model.contents;
        if (type == "textarea") {
            arr.push({
                type: type,
                content: "",
                status: "done",
                type_text: type_text
            });
        } else if (type == "image" || type == "s_image") {
            let index = this.data.model.contents.length;
            this.setData({
                imgSource: 2
            });
            this.uploadImage(type, index);
        } else if (type == "video") {
            wx.showModal({
                title: "",
                content: "上传视频可能需要较长的时间，建议手机连接WIFI环境以免流量损耗",
                showCancel: false,
                complete: res => {
                    if (res.confirm) {
                        this.chooseVideo(-1);
                    }
                }
            });
        }
        this.setData({
            ["model.contents"]: arr
        });
    },
    /**
   * 删除模块
   * @param {*} e 
   */
    delModule: function(e) {
        wx.showModal({
            title: "",
            content: "确认删除该模块内容？",
            complete: res => {
                if (res.cancel) {
                    return false;
                }
                if (res.confirm) {
                    let index = e.currentTarget.dataset.index;
                    let arr = this.data.model.contents;
                    arr.splice(index, 1);
                    this.setData({
                        ["model.contents"]: arr
                    });
                }
            }
        });
    },
    /**
 * 删除商品
 * @param {*} e 
 */
    delGood: function(e) {
        let that = this;
        wx.showModal({
            title: "",
            content: "确认删除该商品吗？",
            complete: res => {
                if (res.cancel) {
                    return false;
                }
                if (res.confirm) {
                    let index = e.currentTarget.dataset.index;
                    let arr = that.data.model.products;
                    arr.splice(index, 1);
                    that.setData({
                        ["model.products"]: arr
                    });
                    that.onBlur("", "products");
                }
            }
        });
    },
    /**
   * 上移模块
   * @param {*} e 
   */
    moveUpModule: function(e) {
        var index = e.currentTarget.dataset.index;
        //获取下标
                console.log(index);
        if (index == 0) {
            return false;
        }
        var type = e.currentTarget.dataset.type || "contents";
        // 在wxml里定义一下property 
                var item = e.currentTarget.dataset.item;
        //获取当前点击数组 
                let arr = type == "contents" ? this.data.model.contents : this.data.model.products;
        arr.splice(index - 1, 0, item);
        arr.splice(index + 1, 1);
        if (type == "contents") {
            this.setData({
                ["model.contents"]: arr
            });
        } else if (type == "products") {
            this.setData({
                ["model.products"]: arr
            });
        }
    },
    /**
   * 下移
   * @param {*} e 
   */
    moveDownModule: function(e) {
        var index = e.currentTarget.dataset.index;
        var type = e.currentTarget.dataset.type || "contents";
        var item = e.currentTarget.dataset.item;
        let arr = type == "contents" ? this.data.model.contents : this.data.model.products;
        arr.splice(index + 2, 0, item);
        arr.splice(index, 1);
        if (type == "contents") {
            this.setData({
                ["model.contents"]: arr
            });
        } else if (type == "products") {
            this.setData({
                ["model.products"]: arr
            });
        }
    },
    /**
   * 置顶
   * @param {*} e 
   */
    topModule: function(e) {
        var index = e.currentTarget.dataset.index;
        var item = e.currentTarget.dataset.item;
        let arr = this.data.model.contents;
        arr.splice(index, 1);
        arr.unshift(item);
        this.setData({
            ["model.contents"]: arr
        });
    },
    /**
   * 向下添加模块弹框
   * @param {*} e 
   */
    addModuleShow: function(e) {
        let that = this;
        let index = e.currentTarget.dataset.index;
        // 显示遮罩层
                var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        });
        that.setData({
            addVisible: true,
            animationData: animation.export(),
            add_index: index
        });
        setTimeout(function() {
            animation.translateY(0).step();
            this.setData({
                animationData: animation.export()
            });
        }.bind(this), 200);
    },
    /**
   * 隐藏模块框
   */
    hideModule: function() {
        // 隐藏遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        });
        animation.translateY(300).step();
        this.setData({
            animationData: animation.export()
        });
        setTimeout(function() {
            animation.translateY(0).step();
            this.setData({
                animationData: animation.export(),
                addVisible: false
            });
        }.bind(this), 200);
    },
    /**
  * 向下添加模块
  */
    addModuleDown: function(e) {
        let type = e.currentTarget.dataset.type;
        let type_text = "";
        if (type == "image") {
            type_text = "大图";
        } else if (type == "s_image") {
            type_text = "小图";
        } else if (type == "video") {
            type_text = "视频";
        } else if (type == "textarea") {
            type_text = "文字";
        }
        let arr = this.data.model.contents;
        if (type == "textarea") {
            arr.splice(this.data.add_index + 1, 0, {
                type: type,
                content: "",
                status: "done",
                type_text: type_text
            });
        } else if (type == "image") {
            this.uploadImage(type, "", this.data.add_index + 1);
        } else if (type == "s_image") {
            let obj = {
                type: type,
                content: [],
                status: "done",
                type_text: "小图"
            };
            arr.splice(this.data.add_index + 1, 0, obj);
            this.setData({
                ["model.contents"]: arr,
                imgSource: 2,
                downAdd: 1,
                downIndex: this.data.add_index + 1
            });
            this.uploadImage(type, "", this.data.add_index + 1);
        } else if (type == "video") {
            wx.showModal({
                title: "",
                content: "上传视频可能需要较长的时间，建议手机连接WIFI环境以免流量损耗",
                showCancel: false,
                complete: res => {
                    if (res.confirm) {
                        this.chooseVideo(this.data.add_index + 1);
                    }
                }
            });
        }
        this.setData({
            ["model.contents"]: arr,
            addVisible: false
        });
    },
    recordTitle: function(e) {
        this.setData({
            ["model.name"]: e.detail.value
        });
        this.onBlur("", "name");
    },
    switchChange: function(e) {
        this.setData({
            ["model.recommend"]: e.detail.value
        });
    },
    /**
  * 
  * @param {* input绑定data-} e 
  * @param {*提交传入校验} value 
  */
    onBlur(e, value) {
        let that = this;
        let data = e ? e.currentTarget.dataset.inputid : value;
        switch (data) {
          case "name":
            if (that.data.model.name === "") {
                this.setData({
                    ["submitMsg.name"]: "请输入接龙活动标题"
                });
            } else if (that.data.model.name.length > 100) {
                this.setData({
                    ["submitMsg.name"]: "标题最长100个字符"
                });
            } else {
                this.setData({
                    ["submitMsg.name"]: ""
                });
            }
            break;

          case "active_at":
            if (that.data.model.active_at === "") {
                this.setData({
                    ["submitMsg.active_at"]: "请选择接龙开始时间"
                });
            } else {
                this.setData({
                    ["submitMsg.active_at"]: ""
                });
            }
            break;

          case "active_end":
            if (that.data.model.active_end === "") {
                this.setData({
                    ["submitMsg.active_end"]: "请选择接龙结束时间"
                });
            } else {
                this.setData({
                    ["submitMsg.active_end"]: ""
                });
            }
            break;

          case "img":
            if (that.data.model.img.length == 0) {
                this.setData({
                    ["submitMsg.img"]: "请上传接龙图片"
                });
            } else {
                this.setData({
                    ["submitMsg.img"]: ""
                });
            }
            break;

          case "contents":
            console.log(that.data.content);
            if (that.data.model.contents.length == 0 && that.data.content == "") {
                this.setData({
                    ["submitMsg.contents"]: "请上传接龙内容"
                });
            } else {
                this.setData({
                    ["submitMsg.contents"]: ""
                });
            }
            break;

          case "products":
            if (that.data.model.products.length == 0) {
                this.setData({
                    ["submitMsg.products"]: "请选择接龙商品"
                });
            } else {
                this.setData({
                    ["submitMsg.products"]: ""
                });
            }
            break;

          default:
            break;
        }
    },
    blurC(e) {
        this.data.content = e.detail.value;
    },
    recordValue: function(e) {
        let index = e.currentTarget.dataset.index;
        let arr = this.data.model.contents;
        if (arr.length != 0) {
            arr[index]["status"] = "done";
            arr[index]["content"] = e.detail.value;
        } else {
            //首次点击文字
            let obj = {
                type: "textarea",
                content: e.detail.value,
                status: "done",
                type_text: "文字"
            };
            arr.push(obj);
        }
        this.setData({
            ["model.contents"]: arr
        });
        this.onBlur("", "contents");
    },
    /**
   * 选择门店/平台商品
   * 带当前填写信息
   *
   */
    changeG(e) {
        var that = this;
        if (that.data.goodsType == 1) {
            wx.showModal({
                title: "提示",
                content: "您已选择了实物类商品，如切换为服务类商品将清空已添加商品~",
                complete: res => {
                    if (res.confirm) {
                        that.setData({
                            ["model.products"]: [],
                            selectIds: []
                        });
                        that.tovirtually();
                    }
                }
            });
        } else {
            wx.showModal({
                title: "提示",
                content: "您已选择了服务类商品，如切换为实物类商品将清空已添加商品~",
                complete: res => {
                    if (res.confirm) {
                        that.setData({
                            ["model.products"]: [],
                            selectIds: []
                        });
                        that.selectGoods(e);
                    }
                }
            });
        }
    },
    selectGoods: function(e) {
        let that = this;
        console.log(e);
        let s = e.currentTarget.dataset.s;
        wx.setStorageSync("leaderCreate", JSON.stringify(this.data.model));
        let ids = this.data.model.products.map(item => {
            return Number(item.id);
        });
        this.setData({
            goodsType: 1
        });
        let opeT = this.data.commodity_type;
        if (that.data.opetype == 3 || that.data.opetype == 4) {
            that.setData({
                commodity_type: 2
            });
            if (s != 2) {
                if (that.data.source1 == 2) {
                    opeT = 2;
                    that.setData({
                        source1: 2,
                        opeT: 2
                    });
                } else if (that.data.source1 == 3) {
                    opeT = 2;
                    that.setData({
                        source1: 2,
                        opeT: 2
                    });
                } else {
                    opeT = 1;
                    that.setData({
                        commodity_type: 1,
                        opeT: 1
                    });
                }
            }
        }
        wx.navigateTo({
            // url: `/CommodityWarehouse/list?type=${this.data.commodity_type != 3 ? this.data.commodity_type : this.data.source}&source=1&selectIds=${JSON.stringify(ids)}`,
            url: `/CommodityWarehouse/list?origin=1&type=${opeT}&source=1&selectIds=${JSON.stringify(ids)}`
        });
    },
    tovirtually() {
        if (this.data.opetype == 3 || this.data.opetype == 4) {
            this.setData({
                source1: 3,
                opeT: 3
            });
        }
        wx.setStorageSync("leaderCreate", JSON.stringify(this.data.model));
        let ids = this.data.model.products.map(item => {
            return Number(item.id);
        });
        this.setData({
            goodsType: 2
        });
        wx.navigateTo({
            // url: `/CommodityWarehouse/list?type=${this.data.commodity_type != 3 ? this.data.commodity_type : this.data.source}&source=1&selectIds=${JSON.stringify(ids)}`,
            url: `/leaderPerson/pages/groupDragon/service/service?selectIds=${JSON.stringify(ids)}`
        });
    },
    /**
   * 预览图片
   */
    previewImg: function(e) {
        let url = e.currentTarget.dataset.url;
        let type = e.currentTarget.dataset.type;
        let current = e.currentTarget.dataset.current || "";
        let params = {
            urls: []
        };
        let arr = [];
        if (type == "image") {
            arr.push(url);
        } else if (type == "s_image") {
            let content = e.currentTarget.dataset.content;
            arr = content;
            params.current = url;
        }
        params.urls = arr;
        wx.previewImage(params);
    },
    /**
   * 提交表单
   */
    submitForm: function() {
        let that = this;
        Object.keys(that.data.model).forEach(key => {
            that.onBlur("", key);
        });
        let message = ``;
        Object.keys(that.data.submitMsg).forEach(key => {
            message += that.data.submitMsg[key];
        });
        if (message) {
            wx.showModal({
                title: "提示",
                content: "请完善信息",
                complete: res => {}
            });
            return false;
        }
        if (that.data.model.contents.findIndex(item => item.type == "textarea" && item.content == "") != -1) {
            wx.showModal({
                title: "提示",
                content: "请完善接龙活动内容文字信息",
                complete: res => {}
            });
            return false;
        }
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                },
                complete() {
                    that.confirmInfo();
                }
            });
            // }
                } else {
            that.confirmInfo();
        }
    },
    confirmInfo() {
        let that = this;
        if (that.data.repeatSub) {
            return;
        }
        let products = [];
        that.data.model.products.forEach((item, index) => {
            let obj = {
                id: item.id,
                sort: that.data.model.products.length - 1 - index
            };
            products.push(obj);
        });
        let content = that.data.model.contents;
        content.forEach((item, index) => {
            if (item.type == "textarea") {
                String(item.content).replaceAll("\n", "\\n");
                //保留换行
                        }
        });
        var source = that.data.commodity_type;
        if (that.data.commodity_type == 2 && that.data.goodsType == 2) {
            source = 3;
        }
        if (that.data.opetype == 4) {
            source = that.data.opeT;
        }
        let change_source = 0;
        if (that.data.opetype == 3) {
            source = 4;
            change_source = that.data.source1;
        }
        let params = {
            source: source,
            name: that.data.model.name,
            group_id: that.data.group_id,
            active_at: that.data.model.active_at,
            active_end: that.data.model.active_end,
            recommend: that.data.model.recommend ? 1 : 0,
            img: that.data.model.img.join(","),
            content: content,
            products: products,
            change_source: change_source
        };
        if (that.data.copy_id != "") {
            params["group_id"] = that.data.copy_id;
        }
        let url = `Leader/leader-group/create`;
        if (that.data.edit_id) {
            //编辑请求的路由
            url = `Leader/leader-group/edit`;
            params["group_id"] = that.data.edit_id;
        }
        this.setData({
            repeatSub: true
        });
        common.request({
            endpoint: url,
            data: params,
            method: "post",
            success(res) {
                if (res.code == 0) {
                    wx.removeStorageSync("leaderCreate");
                    wx.showModal({
                        title: "提示",
                        content: `操作成功！`,
                        showCancel: false,
                        complete: res => {
                            if (res.confirm) {
                                that.setData({
                                    repeatSub: false
                                });
                                wx.reLaunch({
                                    url: "/leaderPerson/pages/groupDragon/List/index"
                                });
                                // wx.navigateBack({
                                //   delta:3
                                // })
                                                        }
                        }
                    });
                }
            },
            fail(res) {
                wx.showModal({
                    title: "提示",
                    content: res.message,
                    showCancel: false,
                    complete: res => {
                        if (res.confirm) {
                            that.setData({
                                repeatSub: false
                            });
                        }
                    }
                });
            }
        });
    }
});